import { ref } from 'vue'

/**
 * 模态框组合式函数
 */
export function useModal() {
  const visible = ref(false)
  const loading = ref(false)
  
  const open = () => {
    visible.value = true
  }
  
  const close = () => {
    visible.value = false
  }
  
  const showLoading = () => {
    loading.value = true
  }
  
  const hideLoading = () => {
    loading.value = false
  }
  
  return {
    visible,
    loading,
    open,
    close,
    showLoading,
    hideLoading
  }
}

/**
 * 确认对话框组合式函数
 */
export function useConfirm() {
  const visible = ref(false)
  const title = ref('')
  const content = ref('')
  const loading = ref(false)
  
  let resolveFn: ((value: boolean) => void) | null = null
  
  const confirm = (options: {
    title?: string
    content: string
  }): Promise<boolean> => {
    title.value = options.title || '确认操作'
    content.value = options.content
    visible.value = true
    loading.value = false
    
    return new Promise((resolve) => {
      resolveFn = resolve
    })
  }
  
  const handleConfirm = () => {
    loading.value = true
    if (resolveFn) {
      resolveFn(true)
    }
    visible.value = false
  }
  
  const handleCancel = () => {
    if (resolveFn) {
      resolveFn(false)
    }
    visible.value = false
  }
  
  return {
    visible,
    title,
    content,
    loading,
    confirm,
    handleConfirm,
    handleCancel
  }
}

/**
 * 消息提示组合式函数
 */
export function useMessage() {
  const message = ref('')
  const type = ref<'success' | 'error' | 'warning' | 'info'>('info')
  const duration = ref(3000)
  const visible = ref(false)
  
  let timer: ReturnType<typeof setTimeout> | null = null
  
  const show = (msg: string, msgType: typeof type.value = 'info', autoClose = true) => {
    message.value = msg
    type.value = msgType
    visible.value = true
    
    if (timer) {
      clearTimeout(timer)
    }
    
    if (autoClose && duration.value > 0) {
      timer = setTimeout(() => {
        hide()
      }, duration.value)
    }
  }
  
  const hide = () => {
    visible.value = false
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }
  
  const success = (msg: string, autoClose = true) => show(msg, 'success', autoClose)
  const error = (msg: string, autoClose = true) => show(msg, 'error', autoClose)
  const warning = (msg: string, autoClose = true) => show(msg, 'warning', autoClose)
  const info = (msg: string, autoClose = true) => show(msg, 'info', autoClose)
  
  return {
    visible,
    message,
    type,
    show,
    hide,
    success,
    error,
    warning,
    info
  }
}